package test.api;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import org.bson.types.ObjectId;

import com.jfinal.kit.JsonKit;
import com.mongodb.BasicDBObject;

public class DBObjectUtil {

    /**
     * 通过Plan获得BasicDBObject对象
     * 
     * @param mac
     */
    public static BasicDBObject getDBObjectByPlan(Plan plan) {
        ObjectId id;
        String sId = plan.getId();
        if (sId == null || sId.length() != 24) {
            id = new ObjectId();
        } else {
            id = new ObjectId(sId);
        }
        BasicDBObject doc = new BasicDBObject("_id", id);
        doc.append("name", plan.getName());
        doc.append("users", JsonKit.toJson(plan.getUsers()));
        doc.append("attatch", getBytesFromFile(plan.getAttach()));
        return doc;
    }
    
    /**
     * 文件转化为字节数组
     */
    private static byte[] getBytesFromFile(File f) {
        if (f == null) {
            return null;
        }
        try {
            FileInputStream stream = new FileInputStream(f);
            ByteArrayOutputStream out = new ByteArrayOutputStream(1000);
            byte[] b = new byte[1000];
            int n;
            while ((n = stream.read(b)) != -1)
                out.write(b, 0, n);
            stream.close();
            out.close();
            return out.toByteArray();
        } catch (IOException e) {
        }
        return null;
    }
}